package com.huawei.bitfun.insight.database;

import com.huawei.bitfun.insight.utils.Common;
import org.apache.commons.dbcp2.BasicDataSource;
import org.jetbrains.annotations.Nullable;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

/**
 * 数据库管理
 */
public class ConnectionManager {
    private static final Map<Integer, BasicDataSource> dataSources = new HashMap<>();

    private static final BasicDataSource basicDataSource = new BasicDataSource();

    static {
        basicDataSource.setDriverClassName("org.sqlite.JDBC");
        basicDataSource.setUrl("jdbc:sqlite:" + Common.getInsightExDbFilePath());
        basicDataSource.setInitialSize(1);
        basicDataSource.setMaxTotal(1);
    }

    public static BasicDataSource getDataSource(int datasourceId, String datasourcePath) {
        if (dataSources.containsKey(datasourceId)) {
            return dataSources.get(datasourceId);
        }
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName("org.sqlite.JDBC");
        dataSource.setUrl("jdbc:sqlite:" + datasourcePath);
        dataSource.setInitialSize(1);
        dataSource.setMaxTotal(1);
        dataSources.put(datasourceId, dataSource);
        return dataSource;
    }

    @Nullable
    public static String deleteDataSourceAndGetPath(int datasourceId) throws SQLException {
        BasicDataSource dataSource = dataSources.remove(datasourceId);
        if (dataSource != null) {
            dataSource.close();
            return dataSource.getUrl().replace("jdbc:sqlite:", "");
        }
        return null;
    }
    public static BasicDataSource getBasicDataSource() {
        return basicDataSource;
    }
}
